//
//  FPProtocolPopupView.m
//  FinanceProject
//
//  Created by 陈显摆 on 2025/5/14.
//

#import "FPProtocolPopupView.h"

@interface FPProtocolPopupView () <TTTAttributedLabelDelegate>

@property (nonatomic , strong) NSMutableArray *dataSource;

@end

@implementation FPProtocolPopupView

LazyLoadDataSource(dataSource)

- (void)awakeFromNib {
    
    [super awakeFromNib];
    
    [self.btn1 handleViewControlEvents:UIControlEventTouchUpInside withBlock:^{
       
        if (self.actionHandler) {
            self.actionHandler(1001);
        }
    }];
    
    [self.btn2 handleViewControlEvents:UIControlEventTouchUpInside withBlock:^{
       
        if (self.actionHandler) {
            self.actionHandler(1002);
        }
    }];
    
    self.clipsToBounds = YES;
    self.layer.cornerRadius = 5.f;
    
    self.backgroundColor = UIColor.whiteColor;
    
    self.btn1.clipsToBounds = YES;
    self.btn1.layer.cornerRadius = 22.f;
    self.btn1.layer.borderWidth = 1.f;
    self.btn1.layer.borderColor = [UIColor hexColor:@"#9A9A9A"].CGColor;
    [self.btn1 setTitleColor:[UIColor hexColor:@"#9A9A9A"] forState:(UIControlStateNormal)];
    self.btn1.backgroundColor = UIColor.clearColor;
    
    self.btn2.clipsToBounds = YES;
    self.btn2.layer.cornerRadius = 22.f;
    self.btn2.backgroundColor = MAIN_BLUE_COLOR;
}


- (void)setProtocol:(NSArray *)protocolSource {
    
    NSMutableString *protocolStr = NSMutableString.string;
    
    [self.dataSource removeAllObjects];
    
    for (FPProtocolModel *model in protocolSource) {
        
        [protocolStr appendFormat:@"%@",model.agreementName];
        
        [self.dataSource addObject:model];
    }
    
    NSString *text = [NSString stringWithFormat:@"感谢您使用众鑫花，请仔细阅读%@。当您点击同意并开始使用该服务时，即表示您已理解并同意该条款内容。",protocolStr];
    
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
    
    for (NSInteger i = 0; i < protocolSource.count; i ++) {
        
        FPProtocolModel *model = protocolSource[i];
        NSRange range = [text rangeOfString:[NSString stringWithFormat:@"%@", model.agreementName]];
        [NSString stringToAttribute:attStr color:MAIN_BLUE_COLOR range:range];
        
        [self.contentLab addLinkToURL:[NSURL URLWithString:model.address] withRange:range];
    }
    
    self.contentLab.attributedText = attStr;
    self.contentLab.userInteractionEnabled = YES;
    self.contentLab.delegate = self;
}

- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
    
    for (FPProtocolModel *model in self.dataSource) {
        
        if ([url.absoluteString isEqualToString:model.address]) {
            
            self.protocolDidSelectAction(model);
            return;
        }
    }
}

@end
